package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.product.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.UUID;

/**
 * @author: atguigu
 * @create: 2023-06-07 15:37
 */
@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucketName}")
    private String bucketName;

    @Value("${minio.endpointUrl}")
    private String endpointUrl;

    /**
     * 文件上传
     *
     * @param file
     * @return 上传后在线图片地址
     */
    @Override
    public String fileUpload(MultipartFile file) {
        try {
            //1.判断存储空间"gmall"是否已创建,如果未创建-执行创建存储空间接口  已创建,将文件上传到指定存储空间下
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
            //2.手动指定文件名称-文件名不能重复 日期/UUID文件后缀名
            String folderName = DateUtil.formatDate(new Date());
            String fileName = UUID.randomUUID().toString();
            String extName = StringUtils.substringAfter(file.getOriginalFilename(), ".");
            fileName = folderName + "/" + fileName + "." + extName;
            //2.调用MinIO客户端对象 将文件上传到MinIO中
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build()
            );
            //3.返回上传后图片在线地址,方便前端进行图片预览
            return endpointUrl + "/" + bucketName + "/" + fileName;
        } catch (Exception e) {
            log.error("[商品服务]文件上传异常:{}", e);
            throw new RuntimeException(e);
        }
    }
}
